#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>

#define MAX_DATA 512 
#define MAX_ROWS 100
#define HELP "readme.txt"
#define DBFILE "dbdes.dat"
#define DESKEY "pDE!10&8"
#define DEL() printf("\033[D \033[D")

void cyscanf(char *str, int n, bool show)
{
    int len = 0;
    char ch;
    struct termios old_term;
    struct termios cur_term;
    tcgetattr(STDIN_FILENO, &old_term);
    memcpy(&cur_term, &old_term, sizeof(cur_term));
    cur_term.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
    cur_term.c_cc[VMIN] = 1;
    cur_term.c_cc[VTIME] = 0;
    tcsetattr(STDIN_FILENO, TCSAFLUSH, &cur_term);

    while (1)
    {
        ch = getchar();
        if (ch == '\n') break;
        if (ch == 8 && len > 0)
        {
            // backspace
            len--;
            if(show) DEL();
            continue;
        }
        if (ch == '\33')
        {
            ch = getchar();
            if (ch == '[')
            {
                ch = getchar();
                switch (ch)
                {
                    case 'A':
                        //printf("\nMOVEUP");
                        break;
                    case 'B':
                        //printf("\nMOVEDOWN");
                        break;
                    case 'C':
                        //printf("\nMOVERIGHT");
                        break;
                    case 'D':
                        //printf("\nMOVELEFT");
                        break;
                }
                continue;
            }
        }
        if (ch > 31 && ch <127 && len < n)
        {
            if(show) printf("%c", ch);
            str[len++] = ch;
        }
        fflush(stdout);
    }
    tcsetattr(STDIN_FILENO, TCSAFLUSH, &old_term);
    str[len] = '\0';
    printf("\n");
}
